package cn.edu.gznu.wecampus.core.web;

import javax.validation.ConstraintViolationException;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authz.AuthorizationException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import cn.edu.gznu.wecampus.core.BusinessException;
import cn.edu.gznu.wecampus.core.FrameworkConstant;
import cn.edu.gznu.wecampus.core.service.PropertyService;
import cn.edu.gznu.wecampus.core.utils.RestResponseUtils;
import lombok.extern.slf4j.Slf4j;

@RestControllerAdvice
@Slf4j
public class RestAdvice {
	
	@Autowired
	private PropertyService propertyService;

	@ExceptionHandler
	@ResponseBody
	public RestResponse exceptionHanlder(Exception ex) {
		log.error(ex.getMessage(), ex);
		return RestResponseUtils.fail(FrameworkConstant.ERROR_CODE_SYSTEM, propertyService.getProperty("pointcircle.framework.message.server-error"));
	}
	
	@ExceptionHandler(value = AuthenticationException.class)
	@ResponseBody
	public RestResponse authenticationException(AuthenticationException ex) {
		log.error(ex.getMessage(), ex);
		return RestResponseUtils.fail(FrameworkConstant.ERROR_CODE_UNAUTHEN, ex.getMessage());
	}
	
	@ExceptionHandler(value = AuthorizationException.class)
	@ResponseBody
	public RestResponse authorizationException(AuthorizationException ex) {
		log.error(ex.getMessage(), ex);
		return RestResponseUtils.fail(FrameworkConstant.ERROR_CODE_UNAUTHOR, ex.getMessage());
	}
	
	@ExceptionHandler(value = BindException.class)
	@ResponseBody
	public RestResponse bindException(BindException ex) {
		log.error(ex.getMessage(), ex);
		return RestResponseUtils.fail(FrameworkConstant.ERROR_CODE_PARAMETER_VALID, ex.getMessage());
	}
	
	@ExceptionHandler(value = ConstraintViolationException.class)
	@ResponseBody
	public RestResponse constraintViolationException(ConstraintViolationException ex) {
		log.error(ex.getMessage(), ex);
		return RestResponseUtils.fail(FrameworkConstant.ERROR_CODE_PARAMETER_VALID, ex.getMessage());
	}
	
	@ExceptionHandler(value = BusinessException.class)
	@ResponseBody
	public RestResponse businessException(BusinessException ex) {
		log.error(ex.getMessage(), ex);
		return RestResponseUtils.fail(FrameworkConstant.ERROR_CODE_BUSINESS, ex.getMessage());
	}
}
